#include <QPushButton>
#include <QKeyEvent>

#include "inputdialog.h"
#include "ui_inputdialog.h"
#include "utils.h"

InputDialog::InputDialog(QString const & title, QString const & text,
        QString const & editorHint, QWidget *parent) :
        QDialog(parent),
        ui(new Ui::InputDialog)
{
#ifdef Q_WS_MAEMO_5
    setWindowFlags(Qt::Dialog);
#else
    setWindowFlags(Qt::Popup);
#endif

    ui->setupUi(this);

    ui->verticalLayout->setContentsMargins(10, 10, 10, 10);
    ui->verticalLayout->setSpacing(10);
    
    setWindowTitle(title);
    ui->label->setText(text);
    ui->text->SetExplanation(editorHint);

    setModal(true);
    
    iOkAction = new QAction(this);
    addAction(iOkAction);
    connect(iOkAction, SIGNAL(triggered()), this, SLOT(onOk()));
    connect(ui->okButton, SIGNAL(clicked()), iOkAction, SLOT(trigger()));
    
    iCancelAction = new QAction(this);
    addAction(iOkAction);
    connect(iCancelAction, SIGNAL(triggered()), this, SLOT(onCancel()));
    connect(ui->cancelButton, SIGNAL(clicked()), iCancelAction, SLOT(trigger()));
}

InputDialog::~InputDialog()
{
    delete ui;
}

QSize InputDialog::sizeHint () const
{
    return ui->verticalLayout->sizeHint();
}

void InputDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void InputDialog::onOk() {
    QString str = ui->text->text();
    if (validateText(str)) {
        ui->text->Clear();
        emit textComplete(str);
        accept();
    }
}

void InputDialog::onCancel() {
    ui->text->Clear();
    reject();
}

void InputDialog::keyPressEvent ( QKeyEvent * event  )
{   
    if (event->key() == Qt::Key_Context1 )
    {
        iOkAction->trigger();
        event->accept();
    }
    else if(event->key() == Qt::Key_Context2)
    {
        iCancelAction->trigger();
        event->accept();
    }
    else
    {
        QDialog::keyPressEvent(event);
    }
}

void InputDialog::showEvent(QShowEvent * event)
    {
    QDialog::showEvent(event);
    ui->text->setFocus();
    }
